//
//  XZNewsCaseVC.m
//  Teecloud
//
//  Created by PC on 2018/10/19.
//  Copyright © 2018年 小志. All rights reserved.
//

#import "XZNewsCaseVC.h"
#import <WebKit/WebKit.h>
#import "XZSearchResultVC.h"
//View
#import "HZInputTextView.h"
#import "XZNewsCaseTitleCell.h"
#import "XZNewsCaseKeyCell.h"
#import "XZNewsCaseContentCell.h"
//Model
#import "XZNewsCase.h"
#import "XZRemarkList.h"
#import "XZRemarkUserInfo.h"
@interface XZNewsCaseVC ()<UITableViewDelegate,UITableViewDataSource,WKUIDelegate, WKNavigationDelegate,HZInputTextViewDelagete>
@property (nonatomic, strong) UITableView *tableView;
//wkwebView  wkwebView高度
@property (nonatomic, strong) WKWebView *webView;
@property (nonatomic, assign) CGFloat webViewHeight;
@property (nonatomic, strong) UIScrollView *scrollView;
//评论数据源 模型
@property (nonatomic, assign) NSInteger pageIndex;
@property (nonatomic, strong) XZNewsCase *newsCase;
@property (nonatomic, strong) NSMutableArray *contentArray;
//评论的数量视图跟标签label
@property (weak, nonatomic) IBOutlet UIView *countView;
@property (weak, nonatomic) IBOutlet UILabel *countLabel;


@end
#define NewsCaseTitle @"XZNewsCaseTitleCell"
#define NewsCaseHtml @"XZNewsCaseHtmlCell"
#define NewsCaseKey @"XZNewsCaseKeyCell"
#define NewsCaseContent @"XZNewsCaseContentCell"
@implementation XZNewsCaseVC
#pragma mark - LifeCycle
- (void)dealloc{
    XZLog(@"%s",__FUNCTION__);
    [self.webView.scrollView removeObserver:self forKeyPath:@"contentSize"];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"新闻资讯";
    self.view.backgroundColor = kWhiteColor;
    self.webViewHeight = kScreenHeight;
    [self createWebView];
    self.pageIndex = 0;
    [self getNewsDetailData:NO];
    [self addLeftBarButtonWithImage:[UIImage imageNamed:@"left-white-64"] action:@selector(left_BarButtonItemAction)];
    

}
- (void)left_BarButtonItemAction {
    if (kIsEmptyString(self.typeStr)) {
        [self.navigationController popViewControllerAnimated:YES];
    }else{
        [self.navigationController popToRootViewControllerAnimated:YES];
    }
}

/*
 *获取资讯详情数据
 */
- (void)getNewsDetailData:(BOOL)isRefresh{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:FROM_IOS forKey:@"from"];
    [dict setValue:[XGMArchiverTools cacheForKey:BUSIORGID] forKey:@"busiOrgId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_UserId] forKey:@"userId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_identifierNumber] forKey:@"loginFinger"];
    //新闻资讯id
    [dict setValue:self.newsId forKey:@"id"];
    
    kWeakObject(self)
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [HJNetwork POSTWithURL:[NSString stringWithFormat:@"/ajax-api.ashx?$c=TeeyunApp&$m=GetNewsInfo&$v=%@",VERSION] parameters:dict cachePolicy:HJCachePolicyIgnoreCache callback:^(id responseObject, NSError *error) {
        [MBProgressHUD hideHUDForView:weakself.view animated:YES];
        [weakself.tableView.mj_header endRefreshing];
        if (!error) {
            if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]) {
                [weakself.contentArray removeAllObjects];
                NSDictionary *dataInfo = [responseObject objectForKey:RESULT_NAME_Data];
                XZNewsCase *newsCase = [XZNewsCase mj_objectWithKeyValues:dataInfo];
                weakself.newsCase = newsCase;
                //添加评论数据
                [weakself.contentArray addObjectsFromArray:newsCase.RemarkList];
                //wkwebview加载html
                [weakself.webView loadHTMLString:newsCase.Content baseURL:nil];
                //评论数量 有就显示 没有就隐藏
                NSInteger commentCount = [newsCase.RemarkCount integerValue];
                if (commentCount > 0) {
                    weakself.countLabel.text = [NSString stringWithFormat:@"%ld",commentCount];
                    weakself.countView.hidden = NO;
                }else{
                    weakself.countView.hidden = YES;
                }
                
                [weakself.tableView.mj_footer endRefreshing];
                [weakself.tableView.mj_header endRefreshing];
                
                if (!isRefresh) {
                    [weakself.tableView reloadData];
                }else{
                    NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:3];
                    [weakself.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
                }
                
            }else{
                
                [MBProgressHUD showErrorOrSuc:[responseObject objectForKey:RESULT_NAME_Message] toView:weakself.view];
            }
            
        }else{
            XZLog(@"%@",error);
        }
    }];
}
/*
 *获取更多评论数据
 */
- (void)getContentData{
    self.pageIndex ++;
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:FROM_IOS forKey:@"from"];
    [dict setValue:[XGMArchiverTools cacheForKey:BUSIORGID] forKey:@"busiOrgId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_UserId] forKey:@"userId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_identifierNumber] forKey:@"loginFinger"];
    //新闻资讯id
    [dict setValue:self.newsId forKey:@"id"];
    [dict setValue:@(self.pageIndex) forKey:@"pageIndex"];
    kWeakObject(self)
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [HJNetwork POSTWithURL:[NSString stringWithFormat:@"/ajax-api.ashx?$c=TeeyunApp&$m=GetNewsRemarkList&$v=%@",VERSION] parameters:dict cachePolicy:HJCachePolicyIgnoreCache callback:^(id responseObject, NSError *error) {
        [MBProgressHUD hideHUDForView:weakself.view animated:YES];
        if (!error) {
            if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]) {
                NSArray *contentArray = [responseObject objectForKey:RESULT_NAME_Data];
                NSArray *newsArray = [XZRemarkList mj_objectArrayWithKeyValuesArray:contentArray];
                //添加评论数据
                [self.contentArray addObjectsFromArray:newsArray];
                //评论数量 有就显示 没有就隐藏
                if (self.contentArray.count > 0) {
                    weakself.countLabel.text = [NSString stringWithFormat:@"%ld",self.contentArray.count];
                    weakself.countView.hidden = NO;
                }else{
                    weakself.countView.hidden = YES;
                }
                
                if (contentArray.count>0) {
                    [weakself.tableView.mj_footer endRefreshing];
                    [weakself.tableView.mj_header endRefreshing];
                    NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:3];
                    [weakself.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
                }else{//没有数据的时候就显示暂无数据
                    weakself.tableView.mj_footer.state = MJRefreshStateNoMoreData;
                }
                
            }else{
                [weakself.tableView.mj_footer endRefreshing];
                [weakself.tableView.mj_header endRefreshing];
                [MBProgressHUD showErrorOrSuc:[responseObject objectForKey:RESULT_NAME_Message] toView:weakself.view];
            }
        }else{
            [weakself.tableView.mj_footer endRefreshing];
            [weakself.tableView.mj_header endRefreshing];
            [MBProgressHUD showErrorOrSuc:@"网络异常" toView:weakself.view];
        }
    }];
}

#pragma mark - TableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 4;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    self.tableView.mj_footer.hidden = self.contentArray.count > 0? NO:YES;
    if (self.newsCase) {
        if (section == 3) {
            return self.contentArray.count;
        }else{
            return 1;
        }
    }else{
        return 0;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    kWeakObject(self)
    UITableViewCell *cell = nil;
    if (indexPath.section == 0) {//标题cell
        XZNewsCaseTitleCell *titleCell = [tableView dequeueReusableCellWithIdentifier:NewsCaseTitle];
        titleCell.model = self.newsCase;
        cell = titleCell;
    }else if (indexPath.section == 1){//wkwebView嵌套在cell上
        UITableViewCell *webCell = [tableView dequeueReusableCellWithIdentifier:@"WebViewCell" forIndexPath:indexPath];
        [webCell.contentView addSubview:self.scrollView];
        cell = webCell;
    }else if (indexPath.section == 2){//关键字cell
        XZNewsCaseKeyCell *keyCell = [tableView dequeueReusableCellWithIdentifier:NewsCaseKey];
        keyCell.model = self.newsCase;
        //跳转到搜索结果页面
        keyCell.KeyButtonBlock = ^(NSString * _Nonnull ButtonName) {
            [weakself skipSearchResultController:ButtonName];
        };
        cell = keyCell;
    }else if (indexPath.section == 3){ //评论cell
        XZNewsCaseContentCell *contentCell = [tableView dequeueReusableCellWithIdentifier:NewsCaseContent];
        XZRemarkList *model= self.contentArray[indexPath.row];
        contentCell.model = model;
        contentCell.indexPath = indexPath;
        //点赞Block
        contentCell.likeBlock = ^(XZRemarkList * _Nonnull model, NSIndexPath * _Nonnull indexPath) {
            [weakself giveALike:model refreshIndexPath:indexPath];
        };
        
        cell = contentCell;
    }
    return cell;
}
#pragma mark - TableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    switch (indexPath.section) {
        case 1:
            return self.webViewHeight;
            break;
        case 2:
            //如果没有数据就不显示出来
            if (self.newsCase.KeyList.count > 0) {
                return 50.0f;
            }else{
                return 0.0f;
            }
            break;
        case 3:
            //如果没有数据就不显示出来
            if (self.newsCase.RemarkList.count > 0) {
                XZRemarkList *remarkModel = self.contentArray[indexPath.row];
                return remarkModel.cellHeight;
            }else{
                return 0.0f;
            }
            
            break;
        default:
            return 100.0f;
            break;
    }
}
//搜索接口页面
- (void)skipSearchResultController:(NSString *)name{
    XZSearchResultVC *searchResultVC = [[XZSearchResultVC alloc]init];
    searchResultVC.key = name;
    [self.navigationController pushViewController:searchResultVC animated:true];
}
//评论的触发事件
- (IBAction)commentTapAction:(UITapGestureRecognizer *)sender {
    kWeakObject(self)
    [HZInputTextView showWithConfigurationBlock:^(HZInputTextView *inputTextView) {
        /** 请在此block中设置inputTextView属性 */
        inputTextView.delegate = self;
        inputTextView.placeholder = @"评论内容至少4个字";
    } sendBlock:^BOOL(NSString *text) {
        if(text.length){
            if (text.length > 200) {
                [MBProgressHUD showErrorOrSuc:@"输入的评论大于200" toView:kGHAlertViewKeyWindow];
                return NO;
            }else{
                if (text.length < 4) {
                    [MBProgressHUD showErrorOrSuc:@"评论内容至少4个字" toView:kGHAlertViewKeyWindow];
                    return NO;
                }else{
                    //发起评论
                    [weakself makeComment:text];
                    return YES;//收起键盘
                }
            }
            
        }else{
            [MBProgressHUD showErrorOrSuc:@"请输入评论内容" toView:kGHAlertViewKeyWindow];
            return NO;//不收键盘
        }
    }];
}
//评论
- (void)makeComment:(NSString *)content{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:FROM_IOS forKey:@"from"];
    [dict setValue:[XGMArchiverTools cacheForKey:BUSIORGID] forKey:@"busiOrgId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_UserId] forKey:@"userId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_identifierNumber] forKey:@"loginFinger"];
    [dict setValue:self.newsId forKey:@"newId"];
    [dict setValue:content forKey:@"remarkContent"];
    __weak typeof(self)weakSelf = self;
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [HJNetwork POSTWithURL:[NSString stringWithFormat:@"/ajax-api.ashx?$c=TeeyunApp&$m=PostNewsRemarkInfo&$v=%@",VERSION] parameters:dict cachePolicy:HJCachePolicyIgnoreCache callback:^(id responseObject, NSError *error) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        if (!error) {
            if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]) {
                [MBProgressHUD showErrorOrSuc:@"提交成功" toView:weakSelf.view];
                NSString *msg =[responseObject objectForKey:RESULT_NAME_Message];
                //更新评论数量
                self.countView.hidden = false;
                self.countLabel.text = msg;
                //从新获取数据
                [self getNewsDetailData:YES];
            }else{
                [MBProgressHUD showErrorOrSuc:[responseObject objectForKey:RESULT_NAME_Message] toView:weakSelf.view];
            }
        }else{
            [MBProgressHUD showErrorOrSuc:@"网络异常" toView:weakSelf.view];
        }
    }];
}
#pragma mark -- HZInputTextViewDelagete
- (void)hzInputTextViewWillShow:(HZInputTextView *)inputTextView{
    /** 如果你工程中有配置IQKeyboardManager,并对HZInputTextView造成影响,请在HZInputTextView将要显示时将其关闭 */
    [IQKeyboardManager sharedManager].enableAutoToolbar = NO;
    [IQKeyboardManager sharedManager].enable = NO;
}

- (void)hzInputTextViewWillHide:(HZInputTextView *)inputTextView{
    /** 如果你工程中有配置IQKeyboardManager,并对HZInputTextView造成影响,请在HZInputTextView将要影藏时将其打开 */
    [IQKeyboardManager sharedManager].enableAutoToolbar = YES;
    [IQKeyboardManager sharedManager].enable = YES;
}
//点赞
- (void)giveALike:(XZRemarkList *)model refreshIndexPath:(NSIndexPath *)indexPath{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:FROM_IOS forKey:@"from"];
    [dict setValue:[XGMArchiverTools cacheForKey:BUSIORGID] forKey:@"busiOrgId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_UserId] forKey:@"userId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_identifierNumber] forKey:@"loginFinger"];
    [dict setValue:@(3) forKey:@"type"];
    [dict setValue:model.Id forKey:@"recId"];
    if (!model.IsLike) {
        [dict setValue:@(1) forKey:@"op"];//点赞
    }else{
        [dict setValue:@(2) forKey:@"op"];//取消点赞
    }
    
    kWeakObject(self)
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [HJNetwork POSTWithURL:[NSString stringWithFormat:@"ajax-api.ashx?$c=TeeyunApp&$m=LikeOrUnlike&$v=%@",VERSION] parameters:dict cachePolicy:HJCachePolicyIgnoreCache callback:^(id responseObject, NSError *error) {
        [MBProgressHUD hideHUDForView:weakself.view animated:YES];
        if (!error) {
            if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]) {
                NSString *msg =[responseObject objectForKey:RESULT_NAME_Message];
                if (msg != nil) {
                    [MBProgressHUD showErrorOrSuc:msg toView:weakself.view];
                }
                XZRemarkList *model= self.contentArray[indexPath.row];
                model.IsLike = !model.IsLike;
                
                NSInteger likeCount ;
                if (model.IsLike) {
                    likeCount = [model.LikeCount integerValue] + 1;
                }else{
                    likeCount = [model.LikeCount integerValue] - 1;
                }
                model.LikeCount = @(likeCount);
                //将之前的模型给替换
                [self.contentArray replaceObjectAtIndex:indexPath.row withObject:model];
                [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationNone];
//                [weakself getNewsDetailData:YES];
            }else{
                [MBProgressHUD showErrorOrSuc:[responseObject objectForKey:RESULT_NAME_Message] toView:weakself.view];
            }
            
        }else{
            XZLog(@"%@",error);
        }
    }];
}
//创建wkwebView
- (void)createWebView
{
    WKWebViewConfiguration *wkWebConfig = [[WKWebViewConfiguration alloc] init];
    WKUserContentController *wkUController = [[WKUserContentController alloc] init];
    wkWebConfig.userContentController = wkUController;
    // 自适应屏幕宽度js
    NSString *jSString = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";
    WKUserScript *wkUserScript = [[WKUserScript alloc] initWithSource:jSString injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
    // 添加js调用
    [wkUController addUserScript:wkUserScript];
    
    self.webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 1) configuration:wkWebConfig];
    self.webView.backgroundColor =  kWhiteColor;
    self.webView.opaque = NO;
    self.webView.userInteractionEnabled = NO;
    self.webView.scrollView.bounces = NO;
    self.webView.UIDelegate = self;
    self.webView.navigationDelegate = self;
    [self.webView sizeToFit];
    [self.webView.scrollView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew context:nil];
    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 1)];
    [self.scrollView addSubview:self.webView];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"contentSize"]) {
        // 方法一
        UIScrollView *scrollView = (UIScrollView *)object;
        CGFloat height = scrollView.contentSize.height;
        self.webViewHeight = height;
        self.webView.frame = CGRectMake(0, 0, kScreenWidth, height);
        self.scrollView.frame = CGRectMake(0, 0, kScreenWidth, height);
        self.scrollView.contentSize =CGSizeMake(kScreenWidth, height);
        if (self.newsCase) {//有数据在刷新
            [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:[NSIndexPath indexPathForRow:0 inSection:1], nil] withRowAnimation:UITableViewRowAnimationNone];
        }
    }
}

#pragma mark - Setter
- (NSMutableArray *)contentArray{
    if (!_contentArray) {
        _contentArray = [[NSMutableArray alloc]init];
    }
    return _contentArray;
}
-(UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, DEVICE_WIDTH, DEVICE_HEIGHT-40-kNavBarAndStatusBarHeight) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.tableFooterView = [[UIView alloc]init];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        //注册cell
        [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([XZNewsCaseTitleCell class]) bundle:nil] forCellReuseIdentifier:NewsCaseTitle];
        [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"WebViewCell"];
        [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([XZNewsCaseKeyCell class]) bundle:nil] forCellReuseIdentifier:NewsCaseKey];
        [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([XZNewsCaseContentCell class]) bundle:nil] forCellReuseIdentifier:NewsCaseContent];
        //上下拉刷新
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(getNewsDetailData:)];
        _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(getContentData)];
        [self.view addSubview:_tableView];
    }
    return _tableView;
}
@end
